#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import sys
import argparse
from ctools.subcmd import get_subcmd_classes
from ctools.subcmd.ctbase import CToolsCmd

import logging
from ctools.logext import *

_rlog, _plog, _mlog, _tlog = get_loggers(__file__, __name__, propagate=False)

class HelpCmd(CToolsCmd):
    @classmethod
    def name(cls):
        return 'help'

    @classmethod
    def description(cls):
        return 'help for ctools'

    @classmethod
    def is_match(cls, name) -> bool:
        return name and name in (cls.name(), '-h', '--help')

    def do_command(self, argv:list[str]):
        name_width = 0
        for cls in get_subcmd_classes():
            name = cls.name()
            name_width = max(len(name), name_width)

        for cls in get_subcmd_classes():
            name = cls.name()
            desc = cls.description()
            print(f'    {name:<{name_width}}: {desc}')
        return 0

def main(argv:list=sys.argv):
    if len(argv) == 1:
        print('no command specified, use -h/--help for more information')
        return False

    subcmd = argv[1]
    for cls in get_subcmd_classes():
        if cls.is_match(subcmd):
            return cls().do_command(argv[2:])

    print(f'unknown command: {subcmd}, use -h/--help for more information')
    return False

if __name__ == '__main__':
    if main(argv=sys.argv):
        sys.exit(0)
    else:
        sys.exit(-1)
